//
//  LocalViewModel.swift
//  Trill
//
//  Created by 顾钱想 on 2019/11/10.
//  Copyright © 2019 顾钱想. All rights reserved.
//

import Foundation
import RxDataSources
final class LocalViewModel: RefreshViewModel {
    struct Input{
    }
    struct Output {
        let items: Driver<[SectionModel<String, [LocalItem]>]>
    }
}
extension LocalViewModel: ViewModelable {
    func transform(input: LocalViewModel.Input) -> LocalViewModel.Output {
        let elements = BehaviorRelay<[SectionModel<String, [LocalItem]>]>(value: [])
       //下拉刷新
        let loadNew = refreshOutput.headerRefreshing.then({}())
       .flatMapLatest { [unowned self] _ in
        self.request(lastId: "", position: 0)
       }
       //上拉加载更多
        let loadMore = refreshOutput.footerRefreshing.then({}())
        .flatMapLatest{[unowned self] _ in
           self.request(lastId: "", position: 0)
        }
        // 数据源
        loadNew.drive(onNext: { [weak self] items in
            guard self != nil else { return }
            elements.accept([SectionModel(model: "", items: [items.items])])
        }).disposed(by: disposeBag)

        loadMore.drive(onNext: { [weak self] items in
            guard self != nil else { return }
            var value = elements.value.first?.items ?? []
            value.append(items.items)
            elements.accept([SectionModel(model: "", items: value)])
        }).disposed(by: disposeBag)


       // success 下的刷新状态
       loadNew
       .mapTo(false)
       .drive(refreshInput.headerRefreshState)
       .disposed(by: disposeBag)
       let output = Output(items: elements.asDriver())
       return output
    }
}
extension LocalViewModel {
    func request(lastId: String, position: Int) -> Driver<LocalData> {
        HomeApi.waterfall(position: position, lastId: lastId)
        .request()
        .debug()
        .mapObject(LocalData.self)
        .trackActivity(loading)
        .trackError(refreshError)
        .asDriverOnErrorJustComplete()
    }
}
